package com.ethen.jzvd;


import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.audio.AudioManager;
import ohos.media.common.Source;
import ohos.media.player.Player;

/**
 * Created by Nathen on 2017/11/8.
 * 实现系统的播放引擎
 */
public class JZMediaSystem extends JZMediaInterface implements Player.IPlayerCallback {
    private static final String TAG = "JZMediaSystem";
    public Player mediaPlayer;

    public JZMediaSystem(Jzvd jzvd) {
        super(jzvd);
    }

    @Override
    public void prepare() {
        release();

        threadRunner = EventRunner.create("JZVD");
        mMediaHandlerThread = new EventHandler(threadRunner);

        mMediaHandler = new EventHandler(EventRunner.getMainEventRunner());//主线程还是非主线程，就在这里
        handler = new EventHandler(EventRunner.getMainEventRunner());

        mMediaHandler.postTask(() -> {
            try {
                mediaPlayer = new Player(jzvd.jzvdContext.getApplicationContext());
                mediaPlayer.setAudioStreamType(AudioManager.AudioVolumeType.STREAM_MUSIC.ordinal());
                mediaPlayer.setPlayerCallback(JZMediaSystem.this);
                mediaPlayer.enableSingleLooping(jzvd.jzDataSource.looping);

                Source source = new Source(jzvd.jzDataSource.getCurrentUrl().toString());
                mediaPlayer.setSource(source);
                mediaPlayer.setVideoSurface(SAVED_SURFACE);
                Log.d(TAG, source.getUri());

                mediaPlayer.prepare();
                mediaPlayer.play();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void start() {
        mMediaHandler.postTask(() -> mediaPlayer.play());
    }

    @Override
    public void pause() {
        mMediaHandler.postTask(() -> mediaPlayer.pause());
    }

    @Override
    public boolean isPlaying() {
        return mediaPlayer.isNowPlaying();
    }

    @Override
    public void seekTo(long time) {
        mMediaHandler.postTask(() -> {
            try {
                mediaPlayer.rewindTo((int) time);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void release() {//not perfect change you later
        if (mMediaHandler != null && mMediaHandlerThread != null && mediaPlayer != null) {//不知道有没有妖孽
            EventHandler tmpHandlerThread = mMediaHandlerThread;
            Player tmpMediaPlayer = mediaPlayer;
            JZMediaInterface.SAVED_SURFACE = null;

            mMediaHandler.postTask(() -> {
                tmpMediaPlayer.setVideoSurface(null);
                tmpMediaPlayer.release();
                tmpHandlerThread.removeAllEvent();
            });
            mediaPlayer = null;
        }
    }

    //TODO 测试这种问题是否在threadHandler中是否正常，所有的操作mediaplayer是否不需要thread，挨个测试，是否有问题
    @Override
    public long getCurrentPosition() {
        if (mediaPlayer != null) {
            return mediaPlayer.getCurrentTime();
        } else {
            return 0;
        }
    }

    @Override
    public long getDuration() {
        if (mediaPlayer != null) {
            return mediaPlayer.getDuration();
        } else {
            return 0;
        }
    }

    @Override
    public void setVolume(float leftVolume, float rightVolume) {
        if (mMediaHandler == null) return;
        mMediaHandler.postTask(() -> {
            if (mediaPlayer != null) {
                mediaPlayer.setVolume((leftVolume + rightVolume) / 2);
            }
        });
    }

    @Override
    public void setSpeed(float speed) {
        mediaPlayer.setPlaybackSpeed(speed);
    }

    @Override
    public void setSurface(Surface surface) {
        mediaPlayer.setVideoSurface(surface);
    }


    @Override
    public void surfaceCreated(SurfaceOps surfaceOps) {
        if (jzvd.textureView.getSurfaceOps().isPresent()) {
            SAVED_SURFACE = surfaceOps.getSurface();
            Log.d(TAG, "surface set");
            prepare();
        }
    }

    @Override
    public void surfaceChanged(SurfaceOps surfaceOps, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceOps surfaceOps) {

    }

    @Override
    public void onPrepared() {
        handler.postTask(() -> jzvd.onPrepared());
    }

    @Override
    public void onMessage(int what, int extra) {
        handler.postTask(() -> jzvd.onInfo(what, extra));
    }

    @Override
    public void onError(int what, int extra) {
        handler.postTask(() -> jzvd.onError(what, extra));
    }

    @Override
    public void onResolutionChanged(int width, int height) {
        handler.postTask(() -> jzvd.onVideoSizeChanged(width, height));
    }

    @Override
    public void onPlayBackComplete() {
        handler.postTask(() -> jzvd.onCompletion());
    }

    @Override
    public void onRewindToComplete() {
        handler.postTask(() -> jzvd.onCompletion());
    }

    @Override
    public void onBufferingChange(int percent) {
        handler.postTask(() -> jzvd.setBufferProgress(percent));
    }

    @Override
    public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {

    }

    @Override
    public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {

    }
}
